package com.haitaoit.chengquan.module.center.activity.info;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.center.activity.info.update.UpdateNameActivity;
import com.haitaoit.chengquan.module.center.activity.info.update.UpdatePhoneActivity;
import com.haitaoit.chengquan.module.center.activity.info.update.UpdatePwdActivity;
import com.haitaoit.chengquan.module.center.model.UserInfoModel;
import com.haitaoit.chengquan.module.center_service.activity.xuqiu_order.FaceBackActivity;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetAbserlutePath;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.ZoomBitmap;
import com.haitaoit.chengquan.view.CircleImageView;
import com.haitaoit.chengquan.view.pickerview.OptionsPopupWindow;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

public class CenterInfoActivity extends BaseActivity {
    @ViewInject(R.id.center_img)
    CircleImageView center_img;
    @ViewInject(R.id.info_username)
    TextView        info_username;
    @ViewInject(R.id.info_nickname)
    TextView        info_nickname;
    @ViewInject(R.id.info_sex)
    TextView        info_sex;
    @ViewInject(R.id.info_phone)
    TextView        info_phone;
    @ViewInject(R.id.face_back)
    LinearLayout    face_back;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_center_info);
        setLeftShow(1, R.mipmap.left);
        setTitle_V("我的资料");
        backLeft_V();
        ViewUtils.inject(this);

        httpGetUserInfo();
    }

    @Override
    protected void onResume() {
        info_phone.setText(UserInfoModel.getUser_info().getPhone());
        super.onResume();
    }

    @OnClick({R.id.right, R.id.center_imgll, R.id.info_usernameLL, R.id.info_nicknameLL,
            R.id.center_sexll, R.id.info_phoneLL, R.id.info_updatepwd, R.id.user_exit,R.id.face_back})
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.right:
                break;
            case R.id.center_imgll:
                Dialog dlg = DialogUtil.ShowPhotoDialog(CenterInfoActivity.this, new BackCall() {
                    @Override
                    public void deal(int which, Object... obj) {
                        switch (which) {
                            case R.id.tv_photos:// 图库
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.addCategory(Intent.CATEGORY_OPENABLE);
                                intent.setType("image/*");
                                intent.putExtra("aspectX", 1);
                                intent.putExtra("aspectY", 1);
                                intent.putExtra("outputX", 500);
                                intent.putExtra("outputY", 500);
                                intent.putExtra("crop", "true");
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 2);
                                break;
                            case R.id.tv_camera:
                                Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(in, 2);
                                break;
                        }
                        super.deal(which, obj);
                    }
                });
                dlg.setCanceledOnTouchOutside(true);
                dlg.show();

                DisplayMetrics metric = new DisplayMetrics();
                this.getWindowManager().getDefaultDisplay().getMetrics(metric);
                int width = metric.widthPixels; // 屏幕宽度（像素）
                WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                params.width = width;
                params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                dlg.getWindow().setAttributes(params);
                break;
            case R.id.info_usernameLL:// 用户名
                break;
            case R.id.info_nicknameLL:// 昵称
                intent.setClass(CenterInfoActivity.this, UpdateNameActivity.class);
                intent.putExtra("nick", info_nickname.getText().toString());
                startActivityForResult(intent, 4);
                break;
            case R.id.center_sexll:// 性别
                updateSex();
                break;
            case R.id.info_phoneLL:// 手机
                intent.setClass(CenterInfoActivity.this, UpdatePhoneActivity.class);
                startActivity(intent);
                break;
            case R.id.info_updatepwd:// 修改密码
                intent.setClass(CenterInfoActivity.this, UpdatePwdActivity.class);
                intent.putExtra("type", "center");
                startActivity(intent);
                break;
            case R.id.user_exit:// 退出
                PreferenceUtils.setPrefString("user_id", "");
                PreferenceUtils.setPrefString("account_type", "");
                PreferenceUtils.setPrefString("password", "");
                intent.setClass(CenterInfoActivity.this, LoginActivity.class);
                PreferenceUtils.setPrefString("first","2");
                startActivity(intent);
                finish();
                break;
            case R.id.face_back:
                intent.setClass(CenterInfoActivity.this, FaceBackActivity.class);
                startActivity(intent);

                break;
        }
        super.onClick(v);
    }

    // 查询个人信息
    private void httpGetUserInfo() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.GetUser_model, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            UserInfoModel user_info = gson.fromJson(Response, UserInfoModel.class);
                            UserInfoModel.setUser_info(user_info);
                            ImageLoader.getInstance().displayImage(user_info.getHead_portrait(), center_img);
                            info_username.setText(user_info.getUser_name());
                            info_nickname.setText(user_info.getNet_name());
                            info_sex.setText(user_info.getSex());
                            info_phone.setText(user_info.getPhone());
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 修改性别
    private void httpGetupdate_sex(final String sex) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("sex", sex));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("sex", sex);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getupdate_sex, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            info_sex.setText(sex);
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 修改头像
    private void httpGetUpdateHead(String file, final Bitmap upbitmap) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id",PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        String url = Constant.update_head_portrait
                + "user_id=" + PreferenceUtils.getPrefString("user_id", "")
                + "&sign=" + sign;

        JSONObject json = new JSONObject();
        try {
            json.put("head_portrait", file);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        HttpUtilsSingle.doPost(this, false, url, json, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            center_img.setImageBitmap(upbitmap);
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 记录文件名
    private String filename;
    // 上传的bitmap
    private Bitmap upbitmap;
    private String file = "";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 4:
                if (resultCode == 10) {// 昵称
                    info_nickname.setText(data.getStringExtra("name"));
                }
                break;
            case 1: // 解成bitmap,方便裁剪
                Bitmap bitmap = BitmapFactory.decodeFile(Environment
                        .getExternalStorageDirectory().getPath() + "/" + filename);
                float wight = bitmap.getWidth();
                float height = bitmap.getHeight();
                ZoomBitmap.zoomImage(bitmap, wight / 8, height / 8);
                upbitmap = ZoomBitmap.zoomImage(bitmap, wight / 19, height / 19);
                center_img.setImageBitmap(upbitmap);
                break;
            case 2:
                if (data != null) {
                    upbitmap = null;
                    if (data.getExtras() != null && !("").equals(data.getExtras())) {
                        upbitmap = (Bitmap) data.getExtras().get("data");
                    } else {
                        String str = data.getDataString();
                        if (str == null) {
                            return;
                        }
                        Uri uri = Uri.parse(str);
                        String path = GetAbserlutePath.getPath(this, uri);
                        if (path.endsWith("png") || path.endsWith("jpg")) {// 图片
                            upbitmap = ImageLoader.getInstance().loadImageSync("file://" + path);
                        } else {
                            ToastUtils.showToast("请选择.jpg或.png格式的图片！");
                            return;
                        }
                    }
                    upbitmap = getSmallBitmap(upbitmap);
                    file = bitmapToString(upbitmap);
//                    center_img.setImageBitmap(upbitmap);
                    httpGetUpdateHead(file, upbitmap);
                }
                break;
        }
    }

    // 把bitmap转换成String
    public static String bitmapToString(Bitmap bgimage) {
        Bitmap bm = getSmallBitmap(bgimage);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(Bitmap bgimage) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        // return BitmapFactory.decodeFile(filePath, options);
        return ZoomBitmap.zoomImage(bgimage, bgimage.getWidth()
                / options.inSampleSize, bgimage.getHeight() / options.inSampleSize);
    }

    // 计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    private void updateSex() {
        final ArrayList<String> sexList = new ArrayList<String>();
        sexList.add("男");
        sexList.add("女");
//        sexList.add("保密");
        OptionsPopupWindow popSex = new OptionsPopupWindow(this, "选择性别");
        popSex.setPicker(sexList);
        popSex.setSelectOptions(0);
        popSex.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                httpGetupdate_sex(sexList.get(options1));
            }
        });
        popSex.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupwindow消失的时候恢复成原来的透明度
                backgroundAlpha(1f);
            }
        });
        popSex.showAtLocation(info_sex, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.6f);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; // 0.0-1.0
        getWindow().setAttributes(lp);
    }

//    @Override
//    public void onBackPressed() {
//        super.onBackPressed();
//        String account_type = PreferenceUtils.getPrefString("account_type", "");
//
//        if(TextUtils.equals(account_type,"1")||TextUtils.isEmpty(account_type)) {
//            Intent intent = new Intent();
//            intent.setClass(CenterInfoActivity.this, MainTabActivity.class);
//            intent.putExtra("index", 3);
//            startActivity(intent);
//        }else {
//            Intent intent = new Intent();
//            intent.setClass(CenterInfoActivity.this, MainTabActivityTwo.class);
//            intent.putExtra("index", 3);
//            startActivity(intent);
//        }
//        finish();
//    }
}
